@page "/demo/amis-charts-demo"
@{
    ViewData["Title"] = "Amis Charts 集成演示";
    Layout = "_Layout";
}

<style>
    .demo-container {
        padding: 20px;
        background: #f8f9fa;
        min-height: 100vh;
    }
    
    .demo-header {
        background: white;
        padding: 24px;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        margin-bottom: 24px;
    }
    
    .demo-section {
        background: white;
        padding: 24px;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        margin-bottom: 24px;
    }
    
    .demo-title {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 20px;
    }
    
    .demo-title h3 {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
    }
    
    .demo-badge {
        padding: 4px 12px;
        border-radius: 16px;
        font-size: 12px;
        font-weight: 500;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }
    
    .demo-badge.echarts {
        background: linear-gradient(135deg, #ff6b6b, #ee5a24);
        color: white;
    }
    
    .demo-badge.amis {
        background: linear-gradient(135deg, #4834d4, #686de0);
        color: white;
    }
    
    .demo-badge.comparison {
        background: linear-gradient(135deg, #00d2d3, #54a0ff);
        color: white;
    }
    
    .demo-description {
        color: #666;
        line-height: 1.6;
        margin-bottom: 20px;
    }
    
    .controls-panel {
        background: #f8f9fa;
        padding: 16px;
        border-radius: 6px;
        margin-bottom: 20px;
        border: 1px solid #e9ecef;
    }
    
    .controls-panel .form-group {
        margin-bottom: 16px;
    }
    
    .controls-panel label {
        display: block;
        margin-bottom: 4px;
        font-weight: 500;
        color: #495057;
    }
    
    .controls-panel select,
    .controls-panel input {
        width: 100%;
        padding: 8px 12px;
        border: 1px solid #ced4da;
        border-radius: 4px;
        font-size: 14px;
    }
    
    .btn-group {
        display: flex;
        gap: 8px;
        margin-bottom: 20px;
    }
    
    .btn-demo {
        padding: 8px 16px;
        border: 1px solid #dee2e6;
        background: white;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.3s ease;
    }
    
    .btn-demo:hover {
        background: #f8f9fa;
        border-color: #adb5bd;
    }
    
    .btn-demo.active {
        background: #007bff;
        color: white;
        border-color: #007bff;
    }
    
    .comparison-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 24px;
        margin-top: 20px;
    }
    
    .comparison-item {
        border: 1px solid #e9ecef;
        border-radius: 8px;
        overflow: hidden;
    }
    
    .comparison-header {
        padding: 12px 16px;
        background: #f8f9fa;
        border-bottom: 1px solid #e9ecef;
        font-weight: 600;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    
    .performance-badge {
        font-size: 11px;
        padding: 2px 8px;
        border-radius: 12px;
        background: #e9ecef;
        color: #495057;
    }
    
    .performance-badge.fast {
        background: #d4edda;
        color: #155724;
    }
    
    .performance-badge.normal {
        background: #fff3cd;
        color: #856404;
    }
    
    .alert {
        padding: 15px;
        margin-bottom: 20px;
        border: 1px solid transparent;
        border-radius: 4px;
    }
    
    .alert-danger {
        color: #721c24;
        background-color: #f8d7da;
        border-color: #f5c6cb;
    }
    
    .btn {
        display: inline-block;
        padding: 6px 12px;
        margin-bottom: 0;
        font-size: 14px;
        font-weight: normal;
        line-height: 1.42857143;
        text-align: center;
        white-space: nowrap;
        vertical-align: middle;
        cursor: pointer;
        border: 1px solid transparent;
        border-radius: 4px;
        text-decoration: none;
    }
    
    .btn-primary {
        color: #fff;
        background-color: #007bff;
        border-color: #007bff;
    }
    
    .btn-primary:hover {
        background-color: #0056b3;
        border-color: #0056b3;
    }
    
    @@media (max-width: 768px) {
        .comparison-grid {
            grid-template-columns: 1fr;
        }
        
        .demo-container {
            padding: 10px;
        }
    }
</style>

<div class="demo-container">
    <!-- 页面标题 -->
    <div class="demo-header">
        <h1>📊 Amis Charts 集成演示</h1>
        <p class="demo-description">
            本页面演示了CodeSpirit Cards SDK中两种图表渲染方式的对比：
            <strong>ECharts渲染器</strong>（原有功能）和<strong>Amis Chart渲染器</strong>（新增功能）。
            两种渲染器可以并存使用，开发者可以根据需要选择合适的渲染方式。
        </p>
    </div>

    <!-- 控制面板 -->
    <div class="demo-section">
        <div class="demo-title">
            <h3>🎛️ 控制面板</h3>
        </div>
        <div class="controls-panel">
            <div class="row">
                <div class="col-md-3">
                    <div class="form-group">
                        <label>图表类型</label>
                        <select id="chartType">
                            <option value="line">线图</option>
                            <option value="bar">柱状图</option>
                            <option value="area">面积图</option>
                        </select>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label>主题</label>
                        <select id="chartTheme">
                            <option value="default">默认蓝色</option>
                            <option value="success">成功绿色</option>
                            <option value="warning">警告橙色</option>
                            <option value="danger">危险红色</option>
                            <option value="info">信息青色</option>
                        </select>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label>图表高度</label>
                        <input type="number" id="chartHeight" value="300" min="200" max="600" step="50">
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label>数据点数</label>
                        <input type="number" id="dataPoints" value="7" min="3" max="20" step="1">
                    </div>
                </div>
            </div>
            <div class="btn-group">
                <button class="btn-demo" onclick="generateNewData()">🎲 生成新数据</button>
                <button class="btn-demo" onclick="refreshCharts()">🔄 刷新图表</button>
                <button class="btn-demo" onclick="comparePerformance()">⚡ 性能对比</button>
            </div>
        </div>
    </div>

    <!-- ECharts渲染器演示 -->
    <div class="demo-section">
        <div class="demo-title">
            <h3>📈 ECharts 渲染器</h3>
            <span class="demo-badge echarts">ECharts</span>
        </div>
        <div class="demo-description">
            使用传统的ECharts库渲染图表，功能强大，自定义能力强。
        </div>
        <div id="echarts-demo-container"></div>
    </div>

    <!-- Amis Chart渲染器演示 -->
    <div class="demo-section">
        <div class="demo-title">
            <h3>📊 Amis Chart 渲染器</h3>
            <span class="demo-badge amis">Amis Chart</span>
        </div>
        <div class="demo-description">
            使用Amis Chart组件渲染图表，与Amis主题完美集成，更轻量级。
        </div>
        <div id="amis-chart-demo-container"></div>
    </div>

    <!-- 对比展示 -->
    <div class="demo-section">
        <div class="demo-title">
            <h3>⚖️ 对比展示</h3>
            <span class="demo-badge comparison">对比</span>
        </div>
        <div class="demo-description">
            并排展示两种渲染器的效果，便于直观对比。
        </div>
        <div class="comparison-grid">
            <div class="comparison-item">
                <div class="comparison-header">
                    ECharts 渲染器
                    <span class="performance-badge normal" id="echarts-perf">--</span>
                </div>
                <div id="echarts-comparison"></div>
            </div>
            <div class="comparison-item">
                <div class="comparison-header">
                    Amis Chart 渲染器
                    <span class="performance-badge fast" id="amis-perf">--</span>
                </div>
                <div id="amis-comparison"></div>
            </div>
        </div>
    </div>

    <!-- 功能特性说明 -->
    <div class="demo-section">
        <div class="demo-title">
            <h3>✨ 功能特性对比</h3>
        </div>
        <div class="table-responsive">
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>特性</th>
                        <th>ECharts 渲染器</th>
                        <th>Amis Chart 渲染器</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>依赖库</td>
                        <td>需要ECharts库 (~800KB)</td>
                        <td>使用Amis内置图表 (~0KB)</td>
                    </tr>
                    <tr>
                        <td>加载速度</td>
                        <td>较慢 (需要加载ECharts)</td>
                        <td>更快 (复用Amis资源)</td>
                    </tr>
                    <tr>
                        <td>主题一致性</td>
                        <td>需要手动配置</td>
                        <td>自动与Amis主题同步</td>
                    </tr>
                    <tr>
                        <td>自定义能力</td>
                        <td>非常强大</td>
                        <td>中等 (受限于Amis配置)</td>
                    </tr>
                    <tr>
                        <td>回退机制</td>
                        <td>无</td>
                        <td>有 (自动回退到HTML图表)</td>
                    </tr>
                    <tr>
                        <td>适用场景</td>
                        <td>复杂图表、高度自定义</td>
                        <td>简单图表、快速集成</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
    // 全局变量
    let currentChartData = null;
    let echartsSDK = null;
    let amisSDK = null;

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 检查资源是否已加载
        let checkCount = 0;
        const maxChecks = 20; // 最多检查20次
        
        const checkResources = () => {
            checkCount++;
            console.log(`检查资源加载状态 (${checkCount}/${maxChecks})...`);
            
            if (typeof CodeSpiritCards !== 'undefined') {
                console.log('资源已加载，开始初始化');
                initializeDemo();
            } else if (checkCount < maxChecks) {
                console.log('资源尚未加载，500ms后重试...');
                setTimeout(checkResources, 500);
            } else {
                console.error('资源加载超时');
                showError('资源加载超时。请检查网络连接或刷新页面重试。');
            }
        };
        
        // 立即开始检查
        checkResources();
    });

    /**
     * 初始化演示
     */
    function initializeDemo() {
        console.log('开始初始化演示...');
        console.log('CodeSpiritCards:', typeof CodeSpiritCards);
        
        // 检查依赖
        if (typeof CodeSpiritCards === 'undefined') {
            console.error('CodeSpirit Cards SDK 未找到');
            showError('CodeSpirit Cards SDK 未加载。请确保 cards-sdk.js 文件已正确加载。');
            return;
        }

        try {
            // 初始化SDK实例
            echartsSDK = new CodeSpiritCards.SDK({
                container: '#echarts-demo-container',
                theme: 'default'
            });

            amisSDK = new CodeSpiritCards.SDK({
                container: '#amis-chart-demo-container',
                theme: 'default'
            });

            // 生成初始数据
            generateNewData();
            
            // 绑定控件事件
            bindControlEvents();
            
            console.log('演示页面初始化完成');
        } catch (error) {
            console.error('初始化失败:', error);
            showError(`初始化失败: ${error.message}`);
        }
    }

    /**
     * 绑定控件事件
     */
    function bindControlEvents() {
        document.getElementById('chartType').addEventListener('change', refreshCharts);
        document.getElementById('chartTheme').addEventListener('change', refreshCharts);
        document.getElementById('chartHeight').addEventListener('change', refreshCharts);
        document.getElementById('dataPoints').addEventListener('change', function() {
            generateNewData();
            refreshCharts();
        });
    }

    /**
     * 生成新数据
     */
    function generateNewData() {
        const dataPoints = parseInt(document.getElementById('dataPoints').value);
        const categories = [];
        const values = [];
        
        for (let i = 0; i < dataPoints; i++) {
            categories.push(`项目${i + 1}`);
            values.push(Math.floor(Math.random() * 100) + 20);
        }
        
        currentChartData = {
            chartTitle: '演示数据',
            xData: categories,
            yData: values
        };
        
        console.log('生成新数据:', currentChartData);
    }

    /**
     * 刷新图表
     */
    async function refreshCharts() {
        if (!currentChartData) {
            generateNewData();
        }
        
        const chartType = document.getElementById('chartType').value;
        const theme = document.getElementById('chartTheme').value;
        const height = parseInt(document.getElementById('chartHeight').value);
        
        const chartData = {
            ...currentChartData,
            chartType: chartType
        };
        
        // 渲染ECharts版本
        await renderEChartsDemo(chartData, theme, height);
        
        // 渲染Amis Chart版本
        await renderAmisChartDemo(chartData, theme, height);
        
        // 渲染对比版本
        await renderComparison(chartData, theme, height);
    }

    /**
     * 渲染ECharts演示
     */
    async function renderEChartsDemo(chartData, theme, height) {
        const cards = [{
            id: 'echarts-demo',
            type: 'chart',
            title: `ECharts ${chartData.chartType.toUpperCase()} 图表`,
            subtitle: '使用ECharts渲染器',
            style: { theme, height },
            data: chartData
        }];
        
        try {
            await echartsSDK.render('#echarts-demo-container', cards);
            console.log('ECharts演示渲染完成');
        } catch (error) {
            console.error('ECharts演示渲染失败:', error);
        }
    }

    /**
     * 渲染Amis Chart演示
     */
    async function renderAmisChartDemo(chartData, theme, height) {
        const cards = [{
            id: 'amis-chart-demo',
            type: 'amis-chart',
            title: `Amis ${chartData.chartType.toUpperCase()} 图表`,
            subtitle: '使用Amis Chart渲染器',
            style: { theme, height },
            data: chartData
        }];
        
        try {
            await amisSDK.render('#amis-chart-demo-container', cards);
            console.log('Amis Chart演示渲染完成');
        } catch (error) {
            console.error('Amis Chart演示渲染失败:', error);
        }
    }

    /**
     * 渲染对比
     */
    async function renderComparison(chartData, theme, height) {
        const echartsConfig = {
            id: 'comparison-echarts',
            type: 'chart',
            title: 'ECharts',
            style: { theme, height: 250 },
            data: chartData
        };
        
        const amisConfig = {
            id: 'comparison-amis',
            type: 'amis-chart',
            title: 'Amis Chart',
            style: { theme, height: 250 },
            data: chartData
        };
        
        try {
            const echartsSDKComp = new CodeSpiritCards.SDK();
            const amisSDKComp = new CodeSpiritCards.SDK();
            
            await echartsSDKComp.render('#echarts-comparison', [echartsConfig]);
            await amisSDKComp.render('#amis-comparison', [amisConfig]);
            
            console.log('对比渲染完成');
        } catch (error) {
            console.error('对比渲染失败:', error);
        }
    }

    /**
     * 性能对比
     */
    async function comparePerformance() {
        console.log('开始性能对比...');
        
        // 测试ECharts性能
        const echartsStart = performance.now();
        await renderEChartsDemo(currentChartData, 'default', 300);
        const echartsEnd = performance.now();
        const echartsTime = echartsEnd - echartsStart;
        
        // 测试Amis Chart性能
        const amisStart = performance.now();
        await renderAmisChartDemo(currentChartData, 'default', 300);
        const amisEnd = performance.now();
        const amisTime = amisEnd - amisStart;
        
        // 更新性能显示
        document.getElementById('echarts-perf').textContent = `${echartsTime.toFixed(1)}ms`;
        document.getElementById('amis-perf').textContent = `${amisTime.toFixed(1)}ms`;
        
        // 更新性能标签
        const echartsLabel = document.getElementById('echarts-perf');
        const amisLabel = document.getElementById('amis-perf');
        
        if (echartsTime < amisTime) {
            echartsLabel.className = 'performance-badge fast';
            amisLabel.className = 'performance-badge normal';
        } else {
            echartsLabel.className = 'performance-badge normal';
            amisLabel.className = 'performance-badge fast';
        }
        
        console.log('性能对比完成:', {
            echarts: `${echartsTime.toFixed(1)}ms`,
            amis: `${amisTime.toFixed(1)}ms`
        });
    }

    /**
     * 显示错误信息
     */
    function showError(message) {
        const errorHtml = `
            <div class="demo-container">
                <div class="demo-section">
                    <div class="alert alert-danger">
                        <h4>⚠️ 加载错误</h4>
                        <p><strong>错误信息:</strong> ${message}</p>
                        <hr>
                        <p><strong>调试信息:</strong></p>
                        <ul>
                            <li>页面URL: ${window.location.href}</li>
                            <li>CodeSpiritCards: ${typeof CodeSpiritCards}</li>
                            <li>脚本加载状态: ${document.querySelector('script[src*="cards-sdk.js"]') ? '已加载' : '未找到'}</li>
                            <li>样式加载状态: ${document.querySelector('link[href*="cards-sdk.css"]') ? '已加载' : '未找到'}</li>
                        </ul>
                        <p><strong>解决方案:</strong></p>
                        <ol>
                            <li>检查 cards-sdk.js 文件是否存在于 /wwwroot/cards-sdk/ 目录</li>
                            <li>确保ASP.NET Core应用正常运行</li>
                            <li>尝试刷新页面</li>
                            <li>查看浏览器控制台了解详细错误</li>
                        </ol>
                        <button onclick="location.reload()" class="btn btn-primary mt-2">🔄 刷新页面</button>
                    </div>
                </div>
            </div>
        `;
        
        document.body.innerHTML = errorHtml;
    }

    // 全局调试函数
    window.demoDebug = function() {
        console.log('=== 演示页面调试信息 ===');
        console.log('当前数据:', currentChartData);
        console.log('ECharts SDK:', echartsSDK);
        console.log('Amis SDK:', amisSDK);
        console.log('控件值:', {
            chartType: document.getElementById('chartType').value,
            theme: document.getElementById('chartTheme').value,
            height: document.getElementById('chartHeight').value,
            dataPoints: document.getElementById('dataPoints').value
        });
    };
</script>

@section Scripts {
    @* <script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/5.4.0/echarts.min.js"></script> *@
    <script src="~/cards-sdk/cards-sdk.js"></script>
    <script src="~/cards-sdk/amis-integration.js"></script>
}

@section Styles {
    <link rel="stylesheet" href="~/cards-sdk/cards-sdk.css" />
} 